﻿/*
 * Project: IV:MP GUI Editor (http://code.google.com/p/ivmp-gui-editor)
 * Code license: GNU Lesser GPL (http://www.gnu.org/copyleft/lesser.html)
 * 
 * Authors: CrackHD
 * Description: application startup code
 */

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;

namespace IvmpEditor
{
    public partial class App : Application
    {
        public static LockFile lockLoading;
        public readonly static Process OwnProcess = Process.GetCurrentProcess();

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Set working directory to executable's location (so setting workdir from shell will not work...):
            Directory.SetCurrentDirectory(new FileInfo(OwnProcess.MainModule.FileName).DirectoryName);
            ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;

            // Execute special working modes
            if (ExecuteArgsCommand(e.Args))
                Shutdown(0);

            // Ensure work directory(s) exists:
            Common.DirUserAppData.Create();
            Common.DirCommonAppData.Create();

            // Hold loading lock:
            lockLoading = new LockFile("loading.lock");
            if (lockLoading.TryHold(20 * 1000) == false)
                Shutdown(-2);

            // Check if we have startup arguments, and there is a pipe server running:
            if (NamedPipes.IsAnyServerAlreadyRunning())
            {
                NamedPipes.SendCommandToServer(eIDECommand.OpenFileAuto, e.Args);
                Shutdown(-1);
            }

            // Load config file:
            Settings.Load();

            // Localize main app thread, if needed:
            var targetUiCulture = Settings.LocalizeCulture;
            if (targetUiCulture != "auto")
                ResourceManager.LocalizeThread(Thread.CurrentThread, targetUiCulture);
        }

        public bool ExecuteArgsCommand(string[] args)
        {
            if (args.Length > 0)
            {
                try
                {
                    switch (args[0].ToLower())
                    {
                        case "-install":        // Post-installation script
                            return true;

                        case "-uninstall":      // Pre-UNinstallation script:
                            Common.DeleteDirectory(Common.DirUserAppData);
                            Common.DeleteDirectory(Common.DirCommonAppData);
                            return true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Unexpected error: {0}", ex.Message), ex.GetType().Name);
                    return true;
                }
            }

            return false;
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            if(Settings.IsLoaded)
                Settings.Save();

            NamedPipes.StopServer();            lockLoading.Release();
        }                            

        public new void Shutdown(int exitCode)
        {            
            OnExit(ExitEventArgs.Empty as ExitEventArgs); // Fixes Shutdown() not calls Exit event, why?
            Environment.Exit(exitCode);
        }
    }
}